//package com.mezz.bones.framework.payment.wxpay;
//
//
//import cn.hutool.core.util.StrUtil;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.TypeReference;
//import com.mezz.bones.framework.payment.domain.request.PayRequest;
//import com.mezz.bones.framework.payment.domain.response.PayResponse;
//import com.mezz.bones.framework.payment.service.IPayService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.util.EntityUtils;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.math.RoundingMode;
//import java.util.Map;
//
//@ConditionalOnBean(WxHttpClientConfig.class)
//@Service
//@Slf4j
//public class WxPayServiceImpl implements IPayService {
//
//  @Resource
//  private CloseableHttpClient httpClient;
//  @Resource
//  private WxpayProperties wxpayProperties;
//
//  @Override
//  public PayResponse pay(PayRequest payRequest) {
//    String payUrl;
//    switch (payRequest.getPaySubChannel()) {
//      case "pc":
//        payUrl=wxpayProperties.getPCPayUrl();
//        break;
//      case "app":
//      default:
//        payUrl=wxpayProperties.getPayUrl();
//    }
//    HttpPost httpPost = new HttpPost(payUrl);
//    WxPayRequest wxPayRequest = new WxPayRequest();
//    wxPayRequest.setAppid(wxpayProperties.getAppId());
//    wxPayRequest.setNotify_url(wxpayProperties.getNotifyUrl());
//    wxPayRequest.setMchid(wxpayProperties.getMchId());
//    wxPayRequest.setOut_trade_no(payRequest.getTradeOutNo());
//    wxPayRequest.setDescription(StrUtil.isBlank(payRequest.getDescription()) ? "宜日达" : payRequest.getDescription());
//    WxPayRequest.AmountDTO amountDTO = new WxPayRequest.AmountDTO();
//    amountDTO.setCurrency(payRequest.getCurrency());
//    amountDTO.setTotal(Math.toIntExact(payRequest.getAmount()));
//    wxPayRequest.setAmount(amountDTO);
//    String reqdata = JSON.toJSONString(wxPayRequest);
//    StringEntity entity = new StringEntity(reqdata, "utf-8");
//    entity.setContentType("application/json");
//    httpPost.setEntity(entity);
//    httpPost.setHeader("Accept", "application/json");
//    //完成签名并执行请求
//
//    try {
//      CloseableHttpResponse response = httpClient.execute(httpPost);
//      try {
//        int statusCode = response.getStatusLine().getStatusCode();
//        if (statusCode == 200) { //处理成功
//          String s = EntityUtils.toString(response.getEntity());
//          Map<String, String> map = JSON.parseObject(s, new TypeReference<Map<String, String>>() {
//          });
//          String result;
//          PayResponse payResponse = new PayResponse();
//          if("pc".equals(payRequest.getPaySubChannel())){
//            result = map.get("code_url");
//          }else {
//            result = map.get("prepay_id");
//            log.info("success,return body = " + EntityUtils.toString(response.getEntity()));
//            Long timestamp = System.currentTimeMillis() / 1000;
//            try {
//              Map<String, Object> signMap = WxHelper.sign(result, timestamp, wxpayProperties);
//              payResponse.setOtherMap(signMap);
//            } catch (Exception e) {
//              log.error("生成签名信息失败");
//              e.printStackTrace();
//            }
//          }
//
//          //生成与支付账单
//          payResponse.setActionVal(result);
//          payResponse.setPayChannel(payRequest.getPayChannel());
//          payResponse.setPaySubChannel(payRequest.getPaySubChannel());
//          payResponse.setAmount(new BigDecimal(payRequest.getAmount()).divide(new BigDecimal("100"), 2, RoundingMode.DOWN).toPlainString());
//          payResponse.setCurrency(payRequest.getCurrency());
//          payResponse.setPayStatus(PayResponseEnum.NOTPAID.name());
//          payResponse.setActionType("pc".equals(payRequest.getPaySubChannel()) ? PayResponse.ACTION_TYPE_IMG : PayResponse.ACTION_TYPE_CODE);
//          payResponse.setTradeOutNo(payRequest.getTradeOutNo());
//          return payResponse;
//        } else if (statusCode == 204) { //处理成功，无返回Body
//          log.info("处理成功，无返回Body: {}");
//        } else {
//          log.info("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
//          throw new IOException("request failed");
//        }
//      } finally {
//        response.close();
//      }
//      System.out.println(response);
//      return null;
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//
//    return null;
//  }
//
//  @Override
//  public PaySuccessResponse query(String tradeOutNo) {
//    PaySuccessResponse paySuccessResponse = new PaySuccessResponse();
//    String uri = wxpayProperties.getQueryUrl() + tradeOutNo + "?mchid=" + wxpayProperties.getMchId();
//    System.out.println(uri);
//    HttpGet httpGet = new HttpGet(uri);
//    httpGet.setHeader("Accept", "application/json");
//    try {
//      CloseableHttpResponse response = httpClient.execute(httpGet);
//      int statusCode = response.getStatusLine().getStatusCode();
//      if (statusCode == 200) { //处理成功
//        String s = EntityUtils.toString(response.getEntity());
//
//        //(amount=WxPayQueryResponse.AmountDTO(currency=null, payerCurrency=CNY, payerTotal=null, total=10), appid=wx42a8a1359b21a20f, attach=null, bankType=null, mchid=1628804180, outTradeNo=EDCTU1661478195531JW646T, payer=null, promotionDetail=[], successTime=null, tradeState=NOTPAY, tradeStateDesc=订单未支付, tradeType=null, transactionId=null)
//        //(amount=null, appid=wx42a8a1359b21a20f, attach=, bankType=null, mchid=1628804180, outTradeNo=EDCTU1661479577410T2QV1C, payer=WxPayQueryResponse.PayerDTO(openid=null), promotionDetail=[], successTime=null, tradeState=NOTPAY, tradeStateDesc=订单未支付, tradeType=null, transactionId=null)
//        WxPayQueryResponse wxPayQueryResponse = JSON.parseObject(s, new TypeReference<WxPayQueryResponse>() {
//        });
//        log.info("wxpay query response:{}",response);
//
//        paySuccessResponse.setTotalAmount("0");
//        paySuccessResponse.setPayCurrency("CNY");
//        paySuccessResponse.setTransactionId(wxPayQueryResponse.getTransactionId());
//
//        Integer total = 0;
//        if(wxPayQueryResponse.getAmount() != null){
//          total = wxPayQueryResponse.getAmount().getTotal();
//          BigDecimal divide = new BigDecimal(total.toString()).divide(new BigDecimal("100"), 2, RoundingMode.FLOOR);
//          paySuccessResponse.setTotalAmount(divide.toPlainString());
//          paySuccessResponse.setPayCurrency(wxPayQueryResponse.getAmount().getPayerCurrency());
//        }
//
//        String successTime = wxPayQueryResponse.getSuccessTime();
//        paySuccessResponse.setCreateTime(successTime);
//        paySuccessResponse.setPayStatus("SUCCESS".equals(wxPayQueryResponse.getTradeState())?PayResponseEnum.SUCCESS:PayResponseEnum.FAIL);
//        return paySuccessResponse;
//      }
//    } catch (IOException e) {
//      e.printStackTrace();
//    }
//    return paySuccessResponse;
//  }
//
//  @Override
//  public void refund(RefundRequest request) {
//
//  }
//
//  @Override
//  public String tag() {
//    return WXPAY;
//  }
//}
//
//
